<%@ WebHandler Language="C#" Class="ShowImage" %>

using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;

public class ShowImage : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        // Reading request parameters
        String photoId = context.Request.QueryString["id"];
        String photoType = context.Request.QueryString["type"];
        // Setting up the connection
        String connectionStr = ConfigurationManager.ConnectionStrings["ZALSConnectionString"].ConnectionString;
        SqlConnection sqlConn = new SqlConnection(connectionStr);
        sqlConn.Open();
        
        // Preparing SQL command
        int id = 0;
        String sqlQuery = "";
        if (int.TryParse(photoId, out id)){
            if (photoType.Equals("team_photo")){
                sqlQuery = "SELECT zdjecie FROM druzyny WHERE id_druzyny=@id";
            } else if (photoType.Equals("team_logo")){
                sqlQuery = "SELECT logo FROM druzyny WHERE id_druzyny=@id";
            } else if(photoType.Equals("player_photo")){
                sqlQuery = "SELECT zdjecie FROM ZAWODNICY WHERE id_zawodnika=@id";
            }
        }
        // Creatind sql command
        SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn);
        cmd.Parameters.Add(new SqlParameter("@id", id.ToString()));

        // Getting image from DB
        SqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        // Sending response
        context.Response.ContentType = "image/jpeg";
        if (photoType.Equals("team_photo"))
        {
            if (dr["zdjecie"].ToString() == "")
                context.Response.Redirect("~/images/default_team.PNG");
            context.Response.BinaryWrite((byte[])dr["zdjecie"]);
        }
        else if (photoType.Equals("team_logo"))
        {
            if (dr["logo"].ToString() == "")
                context.Response.Redirect("~/images/default_team.PNG");
            context.Response.BinaryWrite((byte[])dr["logo"]);
        }
        else if (photoType.Equals("player_photo"))
        {
            if (dr["zdjecie"].ToString() == "")
                context.Response.Redirect("~/images/default_player.gif");
            context.Response.BinaryWrite((byte[])dr["zdjecie"]);
        }
        // Cleanup
        dr.Close();
        sqlConn.Close(); 
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}